const express = require('express')

const route = express.Router()

//引入权限校验文件
const isLoginMiddle = require('../middleware/isLoginMiddle')

//引入数据库文件
const addAdvModel = require('../db/model/addAdvModel')

//引入图片转码工具
const formidable = require('formidable')

const fs = require('fs')

const path = require('path')

//书写一个更新修改接口
route.put('/UpDataAdv', isLoginMiddle, async (req, res) => {
  const { _id } = req.query
  // try {
  //   const { advHref } = await addAdvModel.findOne({
  //     _id
  //   })
  //   const imgName = advHref.split('/')[2]
  //   fs.unlink(path.resolve(__dirname, '../upload', imgName), () => {
  //     console.log('删除图片成功');
  //   })
  // } catch (e) {
  //   console.log("删除图片错误" + e.message);
  //   return res.send({
  //     code: 10001,
  //     mesage: "删除图片错误" + e.message,
  //     data: null
  //   })
  // }
  const form = formidable({
    //接收到文件以后,存放的位置
    uploadDir: path.resolve(__dirname, "../upload"),
    //保持文件后缀名
    keepExtensions: true
  })
  form.parse(req, async (err, parames, file) => {
    //从解析的prames拿到前台的数据
    const {
      advTitle,
      advType,
      advOrder
    } = parames

    try {
      //向数据库更新数据
      await addAdvModel.updateOne({
        _id
      }, {
        $set: {
          advTitle,
          advType,
          advOrder,
          advHref: '/upload/' + file.advPic.newFilename,
          updateTime: new Date().toLocaleString()
        }
      })
      return res.send({
        code: 10000,
        mesage: '更新广告成功',
        data: null
      })
    } catch (e) {
      console.log('更新广告失败', e.message);
      return res.send({
        code: 10001,
        mesage: '更新广告失败' + e.message,
        data: null
      })
    }
  })
})

module.exports = route